package org.code.boot.service.common.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.code.boot.common.utils.DateUtils;
import org.code.boot.common.utils.SecurityUtils;
import org.code.boot.common.utils.ServletUtils;
import org.code.boot.common.utils.StringUtils;
import org.code.boot.common.utils.ip.IpUtils;
import org.code.boot.service.system.ISysConfigService;
import org.code.boot.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.code.boot.mapper.common.ComCommentMapper;
import org.code.boot.domain.common.ComComment;
import org.code.boot.service.common.IComCommentService;

/**
 * 通用评论Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-08-27
 */
@Service
public class ComCommentServiceImpl implements IComCommentService
{
    @Autowired
    private ComCommentMapper comCommentMapper;
    
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询通用评论
     * 
     * @param commentId 通用评论主键
     * @return 通用评论
     */
    @Override
    public ComComment selectBizCommentByCommentId(Long commentId)
    {
        return comCommentMapper.selectBizCommentByCommentId(commentId);
    }

    /**
     * 查询通用评论列表
     * 
     * @param comComment 通用评论
     * @return 通用评论
     */
    @Override
    public List<ComComment> selectBizCommentList(ComComment comComment)
    {
        return comCommentMapper.selectBizCommentList(comComment);
    }

    /**
     * 新增通用评论
     * 
     * @param comComment 通用评论
     * @return 结果
     */
    @Override
    public int insertBizComment(ComComment comComment)
    {
        comComment.setCreateTime(DateUtils.getNowDate());
        return comCommentMapper.insertBizComment(comComment);
    }

    /**
     * 修改通用评论
     * 
     * @param comComment 通用评论
     * @return 结果
     */
    @Override
    public int updateBizComment(ComComment comComment)
    {
        comComment.setUpdateTime(DateUtils.getNowDate());
        return comCommentMapper.updateBizComment(comComment);
    }

    /**
     * 批量删除通用评论
     * 
     * @param commentIds 需要删除的通用评论主键
     * @return 结果
     */
    @Override
    public int deleteBizCommentByCommentIds(Long[] commentIds)
    {
        return comCommentMapper.deleteBizCommentByCommentIds(commentIds);
    }

    /**
     * 删除通用评论信息
     * 
     * @param commentId 通用评论主键
     * @return 结果
     */
    @Override
    public int deleteBizCommentByCommentId(Long commentId)
    {
        return comCommentMapper.deleteBizCommentByCommentId(commentId);
    }

    /**
     * 添加评论
     * 
     * @param businessType 业务类型
     * @param businessId 业务ID
     * @param parentId 父评论ID（可为空）
     * @param content 评论内容
     * @return 结果
     */
    @Override
    public AjaxResult addComment(String businessType, Long businessId, Long parentId, String content)
    {
        // 检查业务类型是否允许评论
        String allowTypes = configService.selectConfigByKey("biz.comment.business.types");
        if (!allowTypes.contains(businessType)) {
            return AjaxResult.error("该业务类型不支持评论功能");
        }

        if (StringUtils.isEmpty(content)) {
            return AjaxResult.error("评论内容不能为空");
        }

        // 获取用户信息
        Long userId = null;
        String nickname = "";
        String avatar = "";
        String userIp = IpUtils.getIpAddr(ServletUtils.getRequest());
        
        try {
            userId = SecurityUtils.getUserId();
            nickname = SecurityUtils.getNickName();
            avatar = SecurityUtils.getAvatar();
        } catch (Exception e) {
            // 未登录用户
            String allowAnonymous = configService.selectConfigByKey("biz.comment.allow.anonymous");
            if (!"true".equals(allowAnonymous)) {
                return AjaxResult.error("请先登录");
            }
            userId = 0L;
            nickname = "匿名用户";
        }

        ComComment comComment = new ComComment();
        comComment.setBusinessType(businessType);
        comComment.setBusinessId(businessId);
        comComment.setParentId(parentId != null ? parentId : 0L);
        comComment.setUserId(userId);
        comComment.setNickname(nickname);
        comComment.setAvatar(avatar);
        comComment.setContent(content);
        comComment.setLikeCount(0);
        comComment.setReplyCount(0);
        comComment.setStatus("1");
        comComment.setUserIp(userIp);
        comComment.setCreateBy(userId > 0 ? SecurityUtils.getUsername() : "anonymous");
        comComment.setCreateTime(DateUtils.getNowDate());

        int result = comCommentMapper.insertBizComment(comComment);
        
        // 如果是回复评论，更新父评论的回复数
        if (parentId != null && parentId > 0) {
            comCommentMapper.updateReplyCount(parentId, 1);
        }

        if (result > 0) {
            return AjaxResult.success("评论成功", comComment);
        } else {
            return AjaxResult.error("评论失败");
        }
    }

    /**
     * 获取业务评论树
     * 
     * @param businessType 业务类型
     * @param businessId 业务ID
     * @return 结果
     */
    @Override
    public AjaxResult getCommentTree(String businessType, Long businessId)
    {
        List<ComComment> commentList = comCommentMapper.selectCommentTree(businessType, businessId);
        
        // 构建评论树形结构
        List<ComComment> tree = buildCommentTree(commentList);
        
        Map<String, Object> result = new HashMap<>();
        result.put("commentTree", tree);
        result.put("totalCount", commentList.size());
        
        return AjaxResult.success(result);
    }

    /**
     * 构建评论树形结构
     * 
     * @param commentList 评论列表
     * @return 树形结构
     */
    private List<ComComment> buildCommentTree(List<ComComment> commentList)
    {
        Map<Long, List<ComComment>> childrenMap = new HashMap<>();
        List<ComComment> topComments = new ArrayList<>();

        // 分组：按parent_id分组
        for (ComComment comment : commentList) {
            Long parentId = comment.getParentId();
            if (parentId == 0) {
                topComments.add(comment);
            } else {
                childrenMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(comment);
            }
        }

        // 递归构建树
        buildTree(topComments, childrenMap);
        
        return topComments;
    }

    /**
     * 递归构建树形结构
     */
    private void buildTree(List<ComComment> parentComments, Map<Long, List<ComComment>> childrenMap)
    {
        for (ComComment parent : parentComments) {
            List<ComComment> children = childrenMap.get(parent.getCommentId());
            if (children != null && !children.isEmpty()) {
                buildTree(children, childrenMap);
            }
        }
    }
}